package com.lt.app;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.Settings;
import android.text.TextUtils;

import androidx.annotation.RequiresApi;
import androidx.core.content.FileProvider;

import com.lt.common.StringHelper;
import com.lt.common.UriHelper;
import com.lt.listener.ResultCallBack;

import java.io.File;
import java.util.List;

/**
 * 意图相关工具类
 *
 * @author luotian
 * @version 2016-12-13
 */
public class IntentHelper {

    private static IntentHelper instance;

    private IntentHelper() {
    }

    public static IntentHelper getInstance() {
        if (instance == null) {
            synchronized (IntentHelper.class) {
                instance = new IntentHelper();
            }
        }
        return instance;
    }


    /**
     * 卸载APK
     *
     * @param packageName 包名
     */
    public void uninstallApk(Activity act, String packageName) {
        Uri packageURI = Uri.parse("package:" + packageName);
        Intent intent = new Intent(Intent.ACTION_DELETE, packageURI);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startAct(act, intent);
    }

    /**
     * 运行apk
     *
     * @param packageName 包名
     */
    public void runApk(Activity act, String packageName) {
        PackageManager pManager = act.getPackageManager();
        Intent intent = pManager.getLaunchIntentForPackage(packageName);
        startAct(act, intent);
    }

    /**
     * 获取App具体设置的意图
     *
     * @param packageName 包名
     */
    public void goAppDetailsSettingsIntent(Activity act, String packageName) {
        Intent intent = new Intent("android.settings.APPLICATION_DETAILS_SETTINGS");
        intent.setData(Uri.parse("package:" + packageName));
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startAct(act, intent);
    }

    /**
     * 获取分享文本的意图
     *
     * @param content 分享文本
     */
    public void goShareTextIntent(Activity act, String content) {
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("text/plain");
        intent.putExtra(Intent.EXTRA_TEXT, content);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startAct(act, intent);
    }

    /**
     * 获取分享图片的意图
     *
     * @param content   文本
     * @param imagePath 图片文件路径
     */
    public void goShareImageIntent(Activity act, String content, String imagePath) {
        goShareImageIntent(act, content, new File(imagePath));
    }

    /**
     * 获取分享图片的意图
     *
     * @param content 文本
     * @param image   图片文件
     */
    public void goShareImageIntent(Activity act, String content, File image) {
        if (!image.exists()) return;
        goShareImageIntent(act, content, Uri.fromFile(image));
    }

    /**
     * 获取分享图片的意图
     *
     * @param content 分享文本
     * @param uri     图片uri
     */
    public void goShareImageIntent(Activity act, String content, Uri uri) {
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.putExtra(Intent.EXTRA_TEXT, content);
        intent.putExtra(Intent.EXTRA_STREAM, uri);
        intent.setType("image/*");
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startAct(act, intent);
    }

    /**
     * 获取其他应用组件的意图
     *
     * @param packageName 包名
     * @param className   全类名
     */
    public Intent getComponentIntent(String packageName, String className) {
        return getComponentIntent(packageName, className, null);
    }

    /**
     * 获取其他应用组件的意图
     *
     * @param packageName 包名
     * @param className   全类名
     * @param bundle      bundle
     */
    public Intent getComponentIntent(String packageName, String className, Bundle bundle) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        if (bundle != null)
            intent.putExtras(bundle);
        ComponentName cn = new ComponentName(packageName, className);
        intent.setComponent(cn);
        return intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    }

    /**
     * 获取关机的意图
     * <p>
     * 需添加权限
     * {@code <uses-permission android:name="android.permission.SHUTDOWN"/>}
     * </p>
     */
    public void getShutdownIntent(Activity act) {
        Intent intent = new Intent(Intent.ACTION_SHUTDOWN);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startAct(act, intent);
    }

    /**
     * 获取拍照的意图
     *
     * @param outUri 输出的uri
     * @return 拍照的意图
     */
    public Intent getCaptureIntent(Uri outUri) {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, outUri);
        return intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION
                | Intent.FLAG_ACTIVITY_NEW_TASK);
    }


    /**
     * 安装APK工具类
     *
     * @param context 上下文
     * @param file    apk文件
     */
    public void installAPK(Context context, File file, ResultCallBack callBack) {
        if (file == null || !file.exists()) {
            if (callBack != null) {
                callBack.onFail(new Exception("文件未找到"));
            }
            return;
        }
        try {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.addCategory("android.intent.category.DEFAULT");
            Uri uri;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                uri = FileProvider.getUriForFile(context, context.getPackageName() + ".fileprovider", file);
                context.grantUriPermission(context.getPackageName(), uri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
                // 给目标应用一个临时授权
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                intent.setDataAndType(uri, context.getContentResolver().getType(uri));
                List<ResolveInfo> resInfoList = context.getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
                for (ResolveInfo resolveInfo : resInfoList) {
                    context.grantUriPermission(resolveInfo.activityInfo.packageName, uri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
                }
            } else {
                intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
            }
            context.startActivity(intent);
            if (callBack != null) {
                callBack.onSuccess();
            }
            try {
                android.os.Process.killProcess(android.os.Process.myPid());
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            if (callBack != null) {
                callBack.onFail(e);
            }
        }
    }


    /**
     * @param pathImg 拍摄照片的路径
     */
    public void openCameraForResult(Context context, String pathImg, int requestCode) {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        Uri uri = UriHelper.getInstance().getUriFromFile(new File(pathImg));
        if (Build.VERSION.SDK_INT >= 24) {
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
            // 授予目录临时共享权限
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION
                    | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        } else {
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        }
        ((Activity) context).startActivityForResult(intent, requestCode);
    }

    /**
     * 通过系统隐式意图方式去调用应用市场app详情页
     */
    public void getMarketIntent(Activity act) {
        Uri uri = Uri.parse("market://details?id=" + act.getPackageName());
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startAct(act, intent);
    }


    @RequiresApi(api = Build.VERSION_CODES.O)
    public void startInstallPermissionSettingActivity(Activity activity, int requestCode) {
        Uri packageURI = Uri.parse("package:" + activity.getPackageName());
        //注意这个是8.0新API
        Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageURI);
        activity.startActivityForResult(intent, requestCode);
    }

    public void openWebView(Activity act, String url) {
        if (!TextUtils.isEmpty(url) && act != null) {
            Uri uri = Uri.parse(url);
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            startAct(act, intent);
        }
    }

    /**
     * 模拟home键退出
     */
    public void goHome(Activity act) {
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addCategory(Intent.CATEGORY_HOME);
        startAct(act, intent);
    }

    public void startAct(Activity act, Intent intent) {
        try {
            act.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
